package com.jn.news.ui;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.net.http.SslError;
import android.os.Bundle;
import android.view.View;
import android.webkit.SslErrorHandler;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import androidx.appcompat.app.AppCompatActivity;

import com.jn.news.R;
import com.jn.news.model.JuheNewsDto;
import com.jn.news.model.NewsDto;
import com.jn.news.utils.Constant;
import com.jn.news.utils.DatabaseHelper;
import com.jn.news.utils.SPUtils;
import com.jn.news.utils.StatusBarUtils;
import com.jn.news.utils.ToastUtil;


/**
 * 新闻详情页
 */
public class NewsDetailActivity extends AppCompatActivity implements View.OnClickListener {

    private WebView webView;
    private RelativeLayout rlLeft;
    private ImageView ivCollection;
    private NewsDto tianxingNewsDto;
    private String newsId;
    private SQLiteDatabase db;
    private boolean isCollection;  //是否收藏
    private JuheNewsDto juheNewsDto;
    private String url;
    private String title;
    private String cTime;
    private String source;
    private String picUrl;
    private String url1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        StatusBarUtils.with(this).init3(2, 102);
        setContentView(R.layout.activity_news_detail);
        initView();
        initData();
    }


    private void initView() {

        rlLeft = findViewById(R.id.rl_left);
        ivCollection = findViewById(R.id.iv_collection);
        webView = findViewById(R.id.webview);
    }

    private void initData() {
        tianxingNewsDto = (NewsDto) getIntent().getSerializableExtra(Constant.NEWS_DETAIL);
        juheNewsDto = (JuheNewsDto) getIntent().getSerializableExtra(Constant.JUHE_NEWS_DETAIL);


        if(tianxingNewsDto == null && juheNewsDto != null){
            newsId = juheNewsDto.getUniqueKey();
            url = juheNewsDto.getUrl();
            title = juheNewsDto.getTitle();
            cTime = juheNewsDto.getDate();
            source = juheNewsDto.getAuthor_name();
            picUrl = juheNewsDto.getThumbnail_pic_s();

        }else{
            newsId = tianxingNewsDto.getId();
            url = tianxingNewsDto.getUrl();
            title = tianxingNewsDto.getTitle();
            cTime = tianxingNewsDto.getCtime();
            source = tianxingNewsDto.getSource();
            picUrl = tianxingNewsDto.getPicUrl();
        }
        rlLeft.setOnClickListener(this);
        ivCollection.setOnClickListener(this);
        initWebView();
        webView.setInitialScale(140);
        webView.loadUrl(url);
        //根据新闻id请求获取判断是否收藏过
        isCollection = isNameExists(newsId);
        if (isCollection) {
            ivCollection.setImageResource(R.mipmap.ic_news_collection);
        } else {
            ivCollection.setImageResource(R.mipmap.ic_news_uncollection);
        }
    }

    private void initWebView() {
        webView.setWebViewClient(new MyWebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                return false;// 返回false
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                // 注入 viewport 元标签
                String js = "javascript:var meta = document.createElement('meta');" +
                        "meta.name='viewport';" +
                        "meta.content='width=device-width, initial-scale=1.0, maximum-scale=1.0';" +
                        "document.getElementsByTagName('head')[0].appendChild(meta);";
                view.evaluateJavascript(js, null);
            }
        });
        WebSettings webSettings = webView.getSettings();
        // 让WebView能够执行javaScript
        webSettings.setJavaScriptEnabled(true);
        // 让JavaScript可以自动打开windows
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
        // 设置缓存
//        webSettings.setAppCacheEnabled(true);
        // 设置缓存模式,一共有四种模式
        webSettings.setCacheMode(webSettings.LOAD_CACHE_ELSE_NETWORK);
        // 设置缓存路径
//        webSettings.setAppCachePath("");
        // 支持缩放(适配到当前屏幕)
        webSettings.setSupportZoom(true);
        webSettings.setTextZoom(180);
        webSettings.setMediaPlaybackRequiresUserGesture(false); // 避免系统干扰
        webSettings.setLoadWithOverviewMode(true);
        // 将图片调整到合适的大小
        webSettings.setUseWideViewPort(false);
        // 支持内容重新布局,一共有四种方式
        // 默认的是NARROW_COLUMNS
        webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        // 设置可以被显示的屏幕控制
        webSettings.setDisplayZoomControls(true);
        // 设置默认字体大小
        webSettings.setDefaultFontSize(12);
        //自适应屏幕
        webView.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        webView.getSettings().setLoadWithOverviewMode(true);
        webView.getSettings().setTextZoom(250);

        // 设置WebView属性，能够执行Javascript脚本
        webView.getSettings().setJavaScriptEnabled(true);
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.rl_left) {
            finish();
        } else if (v.getId() == R.id.iv_collection) {
            if (isCollection) {
                //取消收藏
                cancelCollection(newsId);
            } else {
                addCollection();
            }
        }
    }

    /**
     * 添加收藏
     */
    private void addCollection() {
        //初始化创建表
        SQLiteOpenHelper dbHelper = new DatabaseHelper(this);
        // 调用getReadableDatabase()或getWritableDatabase()才算真正创建或打开数据库
        db = dbHelper.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put("news_id", newsId);
        values.put("user_id", (int) SPUtils.get(this, Constant.USERID, 0));
        values.put("title", title);
        values.put("ctime", cTime);
        values.put("source", source);
        values.put("picurl", picUrl);
        values.put("url", url);
        long result = db.insert("collection", null, values);
        if (result > 0) {
            ToastUtil.showToast(this, "收藏成功");
            ivCollection.setImageResource(R.mipmap.ic_news_collection);
            isCollection = true;
        } else {
            ToastUtil.showToast(this, "收藏失败");
        }
        //关闭数据库连接
        db.close();
    }

    private void cancelCollection(String id) {
        SQLiteOpenHelper dbHelper = new DatabaseHelper(this);
        db = dbHelper.getWritableDatabase();
        String selection = "news_id = ?";
        String[] selectionArgs = {String.valueOf(id)};
        // 执行删除操作
        int rowsDeleted = db.delete("collection", selection, selectionArgs);
        db.close();
        // 如果rowsDeleted大于0，则表示删除成功
        if (rowsDeleted > 0) {
            ToastUtil.showToast(this, "取消收藏成功");
            ivCollection.setImageResource(R.mipmap.ic_news_uncollection);
            isCollection = false;
        } else {
            ToastUtil.showToast(this, "取消收藏失败");
        }
    }


    public class MyWebViewClient extends WebViewClient {

        public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
            //解决证书问题，网页显示空白

            handler.proceed();
            //弹出提示框，让用户决定是否继续加载
            //1.用户选择继续加载
            // handler.proceed();
            //2.用户取消
            //handler.cancel()
        }

    }

    public boolean isNameExists(String id) {
        //初始化创建表
        SQLiteOpenHelper dbHelper = new DatabaseHelper(this);
        // 调用getReadableDatabase()或getWritableDatabase()才算真正创建或打开数据库
        db = dbHelper.getWritableDatabase();
        // sql语句 查询name字段为name的值是否存在
        String sql = "SELECT EXISTS(SELECT 1 FROM collection WHERE news_id = ?)";
        Cursor cursor = db.rawQuery(sql, new String[]{id});
        boolean exists = false;
        if (cursor != null && cursor.moveToFirst()) {
            exists = (cursor.getInt(0) == 1);
        }
        if (cursor != null) {
            cursor.close();
        }
        return exists;
    }


}